package cn.gx.struts2.action;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.gx.domain.User;
import cn.gx.service.UserService;
import cn.gx.util.ValidateUtil;

/**
 * 
 * @author always
 *
 */
@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction<User> implements SessionAware{

	/**
	 * 可以反向序列话，远程调用的时候可以用
	 */
	private static final long serialVersionUID = -6832811860965881255L;


	@Resource(name="userService")
	private UserService userService;
	//接受session map
	private Map<String, Object> sessionMap;
	
	
	
	
	
	public String toLoginPage(){
		
		return "loginPage";
	}

	public String doLogin(){
		
		User user=userService.login(model.getEmail(),model.getPassword());
		
		if(user!=null){
			sessionMap.put("user", user);
			return SUCCESS;
		}
		
		return INPUT;
	}
	
	public void validateDoLogin(){
		
		if(!ValidateUtil.isValid(model.getEmail())){
			addFieldError("email", "邮箱是必填项");
		}
		if(!ValidateUtil.isValid(model.getPassword())){
			addFieldError("password", "密码是必填项");
		}
		if(this.hasErrors()){
			return ;
		}
		if(!userService.isRegisted(model.getEmail())){
			addFieldError("email", "该邮箱没有注册!");
		}
	}

	//框架注入 session 的map
	public void setSession(Map<String, Object> session) {
		// TODO Auto-generated method stub
		this.sessionMap=session;
	}
}
